package org.db.admin.modules.sys.controller;


import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import lombok.extern.slf4j.Slf4j;
import org.db.admin.common.LayuiRes;
import org.db.admin.config.shiro.ShiroUtils;
import org.db.admin.modules.sys.entity.SysUser;
import org.db.admin.modules.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author db117
 * @since 2018-02-17
 */
@Controller
@RequestMapping("/sysUser")
@Slf4j
public class SysUserController extends SuperController {

    @Autowired
    private SysUserService sysUserService;

    /**
     * 进入用户详情页面
     */
    @RequestMapping("info")
    public String info(Model model) {
        model.addAttribute("user", sysUserService.selectById(ShiroUtils.getUserEntity().getId()));
        return "sys/user/info";
    }

    /**
     * 进行保存用户
     */
    @PostMapping(value = "save")
    @ResponseBody
    public LayuiRes save(SysUser sysUser) {
        if (sysUserService.updateById(sysUser)) {
            return LayuiRes.getSuccess("修改成功");
        }
        return LayuiRes.getFailure("修改失败");
    }

    /**
     * 进入添加用户页面
     */
    @GetMapping(value = "add")
    public String add() {
        return "sys/user/add";
    }

    /**
     * 进行添加操作
     */
    @PostMapping(value = "add")
    @ResponseBody
    public LayuiRes add(SysUser sysUser) {
        if ("1".equalsIgnoreCase(ShiroUtils.getUserEntity().getId())) {
            String salt = RandomUtil.randomString(16);
            String password = ShiroUtils.sha256(sysUser.getPassword(), salt);
            sysUser.setPassword(password);
            sysUser.setSalt(salt);
            sysUser.setLoginFlag("1");
            sysUserService.insertAllColumn(sysUser);
            return LayuiRes.getFailure("添加成功");
        }
        return LayuiRes.getFailure("添加失败");
    }

    /**
     * 进入列表页面
     */
    @GetMapping(value = "list")
    public String list() {
        return "sys/user/list";
    }

    /**
     * 列表数据查询接口
     */
    @PostMapping(value = "list")
    @ResponseBody
    public LayuiRes list(SysUser sysUser, Page<SysUser> page) {
        EntityWrapper<SysUser> ew = new EntityWrapper<>();
//        ew.setEntity(sysUser);
        ew.like("name", sysUser.getName());
        return LayuiRes.getPage(sysUserService.selectPage(page, ew));
    }
}

